/**
 * Created with JetBrains WebStorm.
 * User: zhaoyanchao
 * Date: 13-7-4
 * Time: 上午10:27
 * To change this template use File | Settings | File Templates.
 */
var http = require('http'),
    mysql = require('mysql'),
    redis = require('redis'),
    weather = require('./getWeather'),
   getcityCode = require('./getcityCode').getcityCode,
    config = require('./config').config;


function show(data){
    var l = data.length;
    for(var i=0;i<l;i++){
        (function(i){
            var cityCode=data[i]['cityCode'];
            var options = {
                hostname: 'www.weather.com.cn',
                port: 80,
                path: '/data/sk/'+cityCode+'.html',
                method: 'GET'
            };
            weather.getWeather(options,function(chunk){
                var str = JSON.parse(chunk);
                var realTimeweather =  str.weatherinfo;
                //id, time, cityName, cityCode, temperature, wind, windScale, humidity, updateTime, text
                var nowtime=Math.round(new Date().getTime()/1000);
                var cityName = realTimeweather.city,
                    cityCode = realTimeweather.cityid,
                    temperature = realTimeweather.temp,
                    wind = realTimeweather.WD,
                    windScale = realTimeweather.WS,
                    humidity = realTimeweather.SD,
                    updateTime = realTimeweather.time;
                var connection = mysql.createConnection(config.daokeMap);
                    connection.connect();
                var sql ="INSERT INTO daokeMap.realTimeWeatherInfo VALUES ('"+"',from_unixtime("+nowtime+"),'"+cityName+"',"+cityCode+",'"+temperature+"','"+wind+"','"+windScale+"','"+humidity+"','"+updateTime+"','"+chunk+"')";
                connection.query(sql,function(err,reply){
                    if (err) throw err;
                        if(reply['affectedRows'] ==1)
                            console.log(cityName+' realTimeweather to Mysql OK!')
                        connection.end();
                    })
                var client = redis.createClient(config.redis_port,config.redis_public_host);
                client.on('error',function(err){
                    console.log('Error: '+err);
                })
                client.HMSET(cityCode+':weather','temp',temperature,'winds',wind,'windscale',windScale,'humidity',humidity,'releaseTime',updateTime,function(err,res){
                    if(err) throw err;
                    console.log(cityName + 'realTimeweather to redis' +res);
                    client.quit();
                })
            });
        })(i)
    }
}
getcityCode(show);